/**经销商面板*/
var  imgStore= new Ext.data.JsonStore({
				        url: 'queryInlayDiamondPic.action',
				        root: 'list',
				        autoLoad :false,
				        fields: ['id',{name:'name',mapping: 'picName'}, 
				        			{name: 'url', mapping: 'picLine'}, 
				        			{name:'size', type: 'float'}, 
				        			{name:'lastmod', type:'date', dateFormat:'timestamp'}]
				    });

var inlayType_Store=new Ext.data.JsonStore({
	data:[{name:'女戒',value:'女戒'},
	{name:'男戒',value:'男戒'},
	{name:'吊坠',value:'吊坠'},
	{name:'耳钉',value:'耳钉'},
	{name:'手链',value:'手链'}],
	fields: ['name','value']
});

///传ID则是修改,否则为新增
function addProxy(inlayDiaId){
	
	var imagePanel=new Ext.form.FieldSet({
		columnWidth: 0.55,
		anchor: '96%',
//		style:'margin-left:10px;',
		title:'图片上传',
		layout : 'vbox',
		layoutConfig : {
			align : 'stretch',
			pack : 'start'
		},
		height:300,
		items:[{
				xtype:'panel',
				height:35,
				frame:false,
				width:'100%',
				layout:'column',
				defaults:{anchor:'80%'},
				items:[{
						xtype:'form',
						id:'pictureUploadForm',
						columnWidth:.8,
						fileUpload: true,
						hideLabel:true,
						items:[{
							hideLabel:true,
							width:'100%',
							id : 'picture_id',
							name:'picture',
							xtype:'fileuploadfield',
							emptyText : '请选择上传图片!',
							buttonText: '浏览'
						}]
					},{
						columnWidth:.2,
						xtype:'button',
						text:'上传',
						handler:function(){
							uploadPicture(Ext.getCmp('pictureUploadForm'));
						}
				}]
			},{
				xtype:'panel',
		        height:220,
		        layout:'fit',
		        frame:false,
		        tbar: new Ext.Toolbar({
				    items  : ['默认图片:', {
				    	id:'defaultPicture_label',
				    	xtype:'label'
				    },"->",{
				    	text:'删除',
				    	handler:function(){
				    		var view=Ext.getCmp('images-view');
				    		var rds=view.getSelectedRecords();
				    		var store=view.getStore();
				    		Ext.each(rds,function(rd){
								store.remove(rd);	
				    		})
				    	}
				    }]
		        }),
		        items: new Ext.DataView({
		        	id:'images-view',
		            store:imgStore,
					tpl: new Ext.XTemplate(
						'<tpl for=".">',
							'<div class="thumb-wrap" id="{name}">',
							'<div class="thumb"><img src="{url}" title="{name}"></div>',
							'<span class="x-editable">{shortName}</span></div>',
						'</tpl>',
						'<div class="x-clear"></div>'
					),
					autoHeight:true,
					multiSelect: true,
					overClass:'x-view-over',
			        itemSelector:'div.thumb-wrap',
			        emptyText: 'No images to display',
			
			        plugins: [
						new Ext.DataView.DragSelector()
					],
			
					prepareData: function(data){
						data.shortName = Ext.util.Format.ellipsis(data.name, 15);
						data.sizeString = Ext.util.Format.fileSize(data.size);
						return data;
					},
					listeners: {
						selectionchange: {
							fn: function(dv,nodes){
								if(nodes.length>0)
									Ext.getCmp('defaultPicture_label').setText(nodes[0].id);
							}
						}
					}
				})
		    }]
	})
		    
		var infoPanel=new Ext.form.FormPanel({
			columnWidth: 0.45,
			id:'diamondInfoPanel',
			height:'100%',
			items:[{
				xtype:'fieldset',
				id:'baseInfo_form',
				labelAlign:'right',
				labelWidth:70,
				anchor: '96%',
				title:'基本信息',
				defaults: {
						anchor: '96%',
						editable: false,
						triggerAction: 'all',
					    mode: 'local',
					    allowBlank :false,
						xtype: 'textfield',
						valueField:'value',
						displayField:'name'
				},
				items: [{
						xtype:'hidden',
						name : 'inlayDiamondId',
						id: 'inlayDiamondId_fl'
					},{
						fieldLabel: '钻托名称',
						name : 'inlayName',
						id: 'userName_fl'
					},{
						fieldLabel: '钻托编号',
						id: 'inlayNumber_fl',
						name : 'inlayNumber'
					},{
						fieldLabel: '钻托类型',
						name : 'inlayType',
						id: 'inlayType_fl',
						xtype: 'combo',
						store:inlayType_Store
					},{
						fieldLabel: '工厂编号',
						name : 'factoryNumber',
						id: 'factoryNumber_fl'
					}]
				},{
				xtype:'fieldset',
				layout :'column',
				anchor: '96%',
				autoHeight:true,
				title:'材质信息',
				items: [{
					labelAlign:'right',
					labelWidth:65,
					xtype : 'container',  
                    autoEl : {},  
                    layout : 'form',
					columnWidth:.58,
					defaults: {
						anchor: '95%',
						allowBlank :true,
						xtype: 'numberfield'
					},
					items:[{
							fieldLabel: '18K价格',
							name : 'k18Price',
							id: 'k18Price_fl'
						},{
							fieldLabel: 'PT900价格',
							id: 'pt900Price_fl',
							name : 'pt900Price'
						},{
							fieldLabel: 'PT950价格',
							name : 'pt950Price',
							id: 'pt950Price_fl',
							store:inlayType_Store
						}]
					},{
						labelAlign:'right',
						labelWidth:30,
						xtype : 'container',  
	                    autoEl : {},  
	                    layout : 'form',
						columnWidth:.42,
						defaults: {
							anchor: '95%',
							allowBlank :true,
							xtype: 'numberfield'
						},
						items:[{
							fieldLabel: '重量',
							name : 'k18Weight',
							id: 'k18wight_fl'
						},{
							fieldLabel: '重量',
							id: 'pt900wight_fl',
							name : 'pt900Weight'
						},{
							fieldLabel: '重量',
							name : 'pt950Weight',
							id: 'pt950wight_fl'
						}]
					}]
				}]
			})
	//客户订单明细
	var win=new Ext.Window({
		title:'经销商订单详细',
		modal :'true',
		width:620,
		resizable :false,
		items:[{
			xtype:"panel",
			layout: 'column',
			frame:true,
			items: [infoPanel,imagePanel]
		}],
		buttons:[{
			text:'保存',
			handler:function(bt,e){
				var baseInfo_form=Ext.getCmp('diamondInfoPanel');
				if(!baseInfo_form.getForm().isValid()){
					Ext.Msg.alert('提示','请填写完整信息');
					return;
				}
				var infoData=panel_gatherData(baseInfo_form);
				if(Ext.isEmpty(infoData.k18Price)
				|| Ext.isEmpty(infoData.pt900Price)
				|| Ext.isEmpty(infoData.pt950Price)
				|| Ext.isEmpty(infoData.k18Weight)
				|| Ext.isEmpty(infoData.pt950Weight)
				|| Ext.isEmpty(infoData.pt950Weight)
				){
					Ext.Msg.alert('提示','请完整填写材质价格重量信息，没有的请输入0');
					return;
				}
				var p=bt.ownerCt.ownerCt;
				var mainPicture=Ext.getCmp('defaultPicture_label').text,hasMainPicture=false;
				var itemData=[];
				Ext.each(imgStore.data.items,function(it){
					itemData.push({
						picLine:it.data.url,
						picName:it.data.name,
						picId:it.data.id,
						isMainPic:it.data.name==mainPicture
					});
					hasMainPicture=hasMainPicture?hasMainPicture:(it.data.name==mainPicture);
				})
//				log.dir(itemData);
				if(!hasMainPicture){
					Ext.Msg.alert('提示','请选择默认图片');
					return;
				}
				var con = new connection({
						url : 'saveInlayDiamond.action',
						params : {
							InlayDiaPicBoStrs:Ext.encode(itemData),
							inlayDiamondStr : Ext.encode(infoData)
						},
						success : function(rep, opt) {
							if (rep.success) {
								imgStore.removeAll();
								Ext.getCmp('images-view').refresh();
								Ext.Msg.alert('恭喜',rep.msg);
								//刷新前端展示
								gridStore.load({});
								orderGrid.getView().refresh();
								//关闭窗口
								p.destroy();
							} else {
								Ext.Msg.alert('提示',rep.msg);
							}
						},
						failure : function(result, response) {
		        			Ext.Msg.alert('异常','系统异常,请联系管理员');
						}
					})
					con.submit();
			}
		},{
			text:'返回',
			handler:function(bt,e){
				imgStore.removeAll();
				Ext.getCmp('images-view').refresh();
								
				var p=bt.ownerCt.ownerCt;
				p.destroy();
			}
		}]
	})
	win.show('',function initData(){
		if(!Ext.isEmpty(inlayDiaId)){
			var con = new connection({
					url : 'queryInlayDiamondDetail.action',
					params : { inlayDiaId :inlayDiaId },
					success : function( rep,opt) {
						if (rep.success) {
//							log.dir(rep);
							panel_initData('diamondInfoPanel','',rep.obj)
							var picName = rep.obj.picture.split('/');
							Ext.getCmp('defaultPicture_label').setText(picName[picName.length-1])
						}
					},
					failure : function(result, response) {
		        		Ext.Msg.alert('异常','系统异常,请联系管理员');
					}
				})
			con.submit();
			
			Ext.apply(imgStore.baseParams,{
				inlayDiaId:inlayDiaId
			})
			imgStore.reload({callback :function(){
				var viwer=Ext.getCmp('images-view');
				viwer.refresh() 
			}});
			
		}
	});
	return win;
}


/**去除返回JSON上firefox自动增加的<prex>符号; */
Ext.override(Ext.form.Action.Submit, {
    // private  
    processResponse: function(response){
        this.response = response;
        //增加下面几句代码就OK啦  
        ////////////////////////  
        var data = response.responseText;
        if (data.indexOf('<pre>') != -1) {
            response.responseText = data.substring(5, data.length - 6);
            this.response = Ext.util.JSON.decode(response.responseText);
        }
        ///////////////////////////       
        if (!response.responseText) {
            return true;
        }
        this.result = this.handleResponse(response);
        return this.result;
    }
});

function uploadPicture(formPanel){
	var name = Ext.getCmp("picture_id").getValue();
	var as = name.split(".");
	if (Ext.isEmpty(name)) {
		Ext.Msg.alert("提示","请选择上传图片！");
		return false;
	}  
	if (as.length <= 1 || ("jpg" != as[as.length - 1] && "jpeg" != as[as.length - 1] && "bmp" != as[as.length - 1] && "gif" != as[as.length - 1] && "png" != as[as.length - 1])) {
		Ext.Msg.alert("图片错误", "上传文件错误，请选择图片文件上传！");
		return false;
	} 
	if(imgStore.getCount()>5){
		Ext.Msg.alert("提示","上传图片不能超过6张!");
		return ;
	}
	
	if(formPanel.getForm().isValid())
			formPanel.getForm().submit({
				method: 'post',
	            url: 'uploadInlayDiamond.action',
				waitMsg: '正在上传图片,请稍后...',
				success: function(form, action) {
					var img=Ext.decode(action.response.responseText)
					var rdFn=Ext.data.Record.create({});
					var rd=new rdFn({}),t=imgStore.getTotalCount();
					rd.set('url',webLine+"/"+img.obj.picLine);
					rd.set('id',img.obj.picId);
	                rd.set('name',img.obj.picName);
	                if(t<1){
	                	rd.set('isMainPic',true);
	                	Ext.getCmp('defaultPicture_label').setText(img.obj.picName);
	                }
	                imgStore.insert(t,rd);
	                Ext.getCmp('picture_id').setValue('');
	            },
	            failure: function(form, action) {
					        switch (action.failureType) {
					            case Ext.form.Action.CLIENT_INVALID:
					                Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
					                break;
					            case Ext.form.Action.CONNECT_FAILURE:
					                Ext.Msg.alert('Failure', 'Ajax communication failed');
					                break;
					            case Ext.form.Action.SERVER_INVALID:
					               Ext.Msg.alert('Failure', action.result.msg);
					       }
					    }
	                });
}

function queryManager(params,callback){
	var con = new connection({
						url : 'queryInlayDiamondList.action',
						params : {
							inlayDiaPriFr:params.priceFr,
							inlayDiaPriTo: params.priceFr,
							inlayDiaName:params.name,
							inlayDiaType:params.type,
							inlayDiaCode:params.no
						},
						success : function(rep, opt) {
							callback(rep)
						}
					})
					con.submit();
}